package middleware

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"strings"
	"yxService/app/models"
	"yxService/app/pkg/app"
	"yxService/app/pkg/errcode"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		response := app.NewResponse(c)
		var (
			token string
			ecode = errcode.Success
		)

		authHeader := c.GetHeader("Authorization")

		if authHeader == "" {
			ecode = errcode.InvalidParams
		} else {
			//拆分Authorization 数据
			tokenArr := strings.SplitN(authHeader, " ", 2)
			//token格式错误处理
			if !(len(tokenArr) == 2 && tokenArr[0] == "Bearer") {
				response.ToErrorResponse(nil, errcode.FormalAuthError)
				c.Abort()
				return
			}
			//获取token部分l
			token = tokenArr[1]
			fmt.Println("token is :")
			fmt.Println("bear token")
			fmt.Println(token)
			//验证token
			claims, err := app.ParseToken(token)
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					ecode = errcode.UnauthorizedTokenTimeout
				default:
					ecode = errcode.UnauthorizedTokenError
				}
			}
			//获取登录授权的user实例 并复制到AuthUser/AuthMer
			if claims != nil {
				claims, _ := app.ParseToken(token) //解密token 获取数据
				models.AuthUser = claims.AuthUser
			}
		}

		if ecode != errcode.Success {
			response.ToErrorResponse(ecode, errcode.UnauthorizedTokenError)
			c.Abort()
			return
		}
		c.Next()
	}
}
